import request from '../../request/request.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    courseInfo:'',
    isExpired:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    let options = currentPage.options;
    const { id } = options;
    this.setData({id:id})
    this.getDetail();
  },
  getDetail(){
    var that =this
    request({
      url:'course/detail',
      method:'post',
      data:{id:that.data.id}
    }).then(res=>{
      if(res.data.success){
        this.setData({
          courseInfo:res.data.data,
          isExpired:res.data.data.expired
        })
      }
    }).catch(err=>{})
  },
  /**
   * 预约课程
   */
  reserveCourse(){
    let that =this
    let user = wx.getStorageSync('userInfo');
    if( user == ''){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1500,
        mask: true
      });
      return;
    }
    wx.showModal({
      title: '提示',
      content: '您确认要预约本课程吗?',
      success (res) {
        if (res.confirm) {
          request({
            url:'course/reserve',
            method:'post',
            data:{
              id:that.data.id,
              userId:user.id
            }
          }).then(res=>{
            console.log(res);
            if(res.data.success){
              wx.showToast({
                title: res.data.data,
                icon: 'none',
                duration: 2500,
                mask: true
              });
              //由于有可能修改了用户余额，所以需要更新缓存中的用户数据
              that.updateUser(user.id)
            }else{
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2500,
                mask: true
              });
            }
          }).catch(err=>{})
        } else if (res.cancel) {
          console.log('用户点击取消');
          return;
        }
      }
    })
  },
  //更新缓存中的用户数据
  updateUser(id){
    request({
      url:'user/info',
      method:'post',
      data:{id:id}
    }).then(res=>{
      if(res.data.success){
       wx.setStorageSync('userInfo', res.data.data)
      }
    })
  }
})